package com.spring.showcase.interceptors;

import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.context.request.async.DeferredResultProcessingInterceptorAdapter;

public class DeferredInterceptor extends DeferredResultProcessingInterceptorAdapter {

    @Override
    public <T> void preProcess(NativeWebRequest request, DeferredResult<T> deferredResult) throws Exception {
        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime", startTime, RequestAttributes.SCOPE_REQUEST);
    }

    @Override
    public <T> void postProcess(NativeWebRequest request, DeferredResult<T> deferredResult, Object concurrentResult) throws Exception {
        long startTime = (Long) request.getAttribute("startTime", RequestAttributes.SCOPE_REQUEST);
        System.out.println("execution took: " + (System.currentTimeMillis() - startTime) + " ms");
    }

}
